
const { Pool } = require('pg');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const pool = new Pool({
    user: 'postgres',
    //host: '127.0.0.1',
    host: 'project_data_base',
    database: 'postgres',
    password: '1234',
    port: 5432,
  });

class auth{
  /**
     * @swagger
     * components:
     *   schemas:
     *     User:
     *       type: object
     *       properties:
     *         email:
     *           type: string
     *         password:
     *           type: string
     *         last_name:
     *           type: string
     *         first_name:
     *           type: string
     *         middle_name:
     *           type: string
     *         role_id:
     *           type: integer
     */

    /**
     * @swagger
     * /register:
     *   post:
     *     tags: [Аутентификация и пользователи]
     *     summary: Регистрация нового пользователя
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             $ref: '#/components/schemas/User'
     *     responses:
     *       201:
     *         description: User registered successfully
     *       500:
     *         description: Internal server error
     */
    async registration(req, res) {
        try {
          const { email, password, last_name, first_name, middle_name, role_id } = req.body;
          const hashedPassword = await bcrypt.hash(password, 10);
          const createUserQuery = 'INSERT INTO users (email, password, last_name, first_name, middle_name, role_id) VALUES ($1, $2, $3, $4, $5, $6)'
          await pool.query(createUserQuery, [email, hashedPassword, last_name, first_name, middle_name, role_id])
          res.status(201).send('User registered successfully')
        } catch (error) {
          console.error(error);
          res.status(500).send('Internal server error')
        }
      }
     /**
     * @swagger
     * /login:
     *   post:
     *     tags: [Аутентификация и пользователи]
     *     summary: Логин пользователя
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             type: object
     *             properties:
     *               email:
     *                 type: string
     *               password:
     *                 type: string
     *     responses:
     *       200:
     *         description: Successful login
     *       401:
     *         description: Invalid email or password
     *       500:
     *         description: Internal server error
     */ 
    async login (req, res){
        try {
          const { email, password } = req.body
          console.log(email)
          const getUserQuery = 'SELECT * FROM users WHERE email = $1'
          const { rows } = await pool.query(getUserQuery, [email])
          const user = rows[0]
          
      
          if (!user) {
            return res.status(401).send('Invalid email or password')
          }
      
          const passwordMatch = await bcrypt.compare(password, user.password)
          if (!passwordMatch) {
            return res.status(401).send('Invalid email or password')
          }
      
          const accessToken = jwt.sign({ email: user.email }, 'secret_key', { expiresIn: '24h' })
          const refreshToken = jwt.sign({ email: user.email }, 'refresh_secret_key', { expiresIn: '48h' })
          res.json({ accessToken, refreshToken })
        } catch (error) {
          console.error(error)
          res.status(500).send('Internal server error');
        }
      }
      
      /**
     * @swagger
     * /refresh-token:
     *   post:
     *     tags: [Аутентификация и пользователи]
     *     summary: Обновление access token по refresh token
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             type: object
     *             properties:
     *               refreshToken:
     *                 type: string
     *     responses:
     *       200:
     *         description: Successful token refresh
     *       401:
     *         description: Refresh token is required
     *       403:
     *         description: Invalid refresh token
     *       500:
     *         description: Internal server error
     */
      async refreshToken(req, res){
        const { refreshToken } = req.body;
        if (!refreshToken) {
          return res.status(401).send('Refresh token is required')
        }
        jwt.verify(refreshToken, 'refresh_secret_key', (err, user, u) => {
          if (err) {
            return res.status(403).send('Invalid refresh token')
          }
          console.log(user.email)
          const accessToken = jwt.sign({ email: user.email }, 'secret_key', { expiresIn: '24h' })
          res.json({ accessToken })
        });
      };
      /**
     * @swagger
     * /users:
     *   get:
     *     tags: [Аутентификация и пользователи]
     *     summary: Получение списка пользователей
     *     responses:
     *       200:
     *         description: Successful retrieval of user list
     *         content:
     *           application/json:
     *             schema:
     *               type: object
     *               properties:
     *                 users:
     *                   type: array
     *                   items:
     *                     $ref: '#/components/schemas/User'
     *       500:
     *         description: Internal server error
     */
      async users(res){
        try {
          const queryText = `
            SELECT * FROM users;
          `;
      
          const result = await pool.query(queryText);
          const users = result.rows;
      
      
          const response = {
              users
          };
      
          res.json(response);
        } catch (error) {
          res.status(500).json({ error: error.message });
        }
      };
      
      
}
module.exports = new auth()